package com.cnspt.controllers;

import com.cnspt.models.Users;
import com.cnspt.repository.UsersRepository;
import com.cnspt.utils.Empty;
import com.cnspt.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("account")
public class AccountController {
    @Autowired
    private UsersRepository usersRepository;

    @RequestMapping("login" )
    public String login() {
        return "account/login.html";
    }

    @RequestMapping("/getLoginData")
    @ResponseBody
    public JsonData getLoginData(String username, String password) {
        if(Empty.isNull(username) || Empty.isNull(password)) return JsonData.Error("参数不能为空");
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        try {
            Users user = usersRepository.getUserByNameAndPassword(username, passwordMd5);
            if(user != null) {
                return JsonData.success(user);
            } else {
                return JsonData.Error("error");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JsonData.Error(e.getMessage());
        }
    }

    @RequestMapping("/register")
    public String register() {
        return "account/register.html";
    }

    @RequestMapping("/getRegisterData")
    @ResponseBody
    public JsonData getRegisterData(String username, String password) {
        if(Empty.isNull(username) || Empty.isNull(password)) return JsonData.Error("参数不能为空");
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        try {
            Users users = new Users();
            users.setName(username);
            users.setPassword(passwordMd5);
            users.setSex(1);
            users.setMobile("15949411455");
            Users user = usersRepository.save(users);
            if(user != null) {
                return JsonData.success(user);
            } else {
                return JsonData.Error("error");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JsonData.Error(e.getMessage());
        }
    }

}
